package actions.systools;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.upload.FormFile;

import utils.DBInitiator;

/**
 * 
 * @author sunhy
 * 
 */
public class ImportSqlFileAction extends Action {
    /**
     * 初始化数据库.
     */
    public DBInitiator dbInitor;

    /**
     * @param mapping action mapping
     * @param form action form
     * @param request request
     * @param response response
     * @return action form
     * @throws Exception any exception
     */
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        DynaActionForm uploadForm = (DynaActionForm) form;
        FormFile formfile = (FormFile) uploadForm.get("uploadFile");
        if (formfile.getInputStream() == null) {
            ActionMessages errMsgs = new ActionMessages();
            errMsgs.add("uploadFile", new ActionMessage(
                    "errors.uploadFile.fileName.isEmpty"));
            // 保存错误信息并重定向到输入界面
            this.saveErrors(request, errMsgs);
            return mapping.getInputForward();
        }
        String result = dbInitor.initDBfromSqlFile(formfile.getInputStream());
        request.setAttribute("result", result);
        return mapping.findForward("success");
    }

    /**
     * @param pInitiator the dBInitiator to set
     */
    public void setDbInitor(DBInitiator pInitiator) {
        dbInitor = pInitiator;
    }
}